package cn.jtool.dig.server.timer;

import cn.jtool.dig.common.model.Session;
import cn.jtool.dig.common.netty.SessionManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class TunnelHeartbeatCheckTask {

    private static final long HEARTBEAT_TIMEOUT = 1000 * 20;

    public void run(){
        List<Session> sessions = SessionManager.getSession(Session.SessionType.TUNNEL);
        if(CollectionUtils.isNotEmpty(sessions)){
            long currentTime = System.currentTimeMillis();
            sessions.forEach(session -> {
                if(currentTime - session.getHeartbeatTime() > HEARTBEAT_TIMEOUT){
                    log.error("session: {} 心跳超时, 断开链路", session);
                    try{
                        session.disconnect();
                    }catch (Exception e){
                        log.error("session: {} 断开链路异常", session, e);
                        SessionManager.removeSession(session.getId());
                    }
                }
            });
        }
    }

}
